﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B10.Helpers;
using B10.Models;
using System.IO;

namespace B10.Controllers
{
    [Authorize]
    [HandleError]
    public class UploadController : Controller
    {

        IDatabaseRepository _db;

        public UploadController()
            : this(new DatabaseRepository())
        {
        }

        public UploadController(IDatabaseRepository db)
        {
            _db = db;
        }

        [HttpPost]
        public ActionResult Image(int id)
        {
            if (Request.Files.Count != 1 || Request.Files[0].ContentLength <= 0
                || !ImageHelper.IsCorrectContentType(Request.Files[0].ContentType))
                return View();//View("PopUp", (object)B10.Properties.ValidationMessages.WrongFile);

            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId))
                return new ForbiddenResult();
            try
            {
                GalleryImage img = ImageHelper.SaveImage(Request.Files[0], id.ToString());
                img.PageId = id;
                _db.Add(img);
                _db.Save();
                return View(img);
            }
            catch
            {
                return View();//View("PopUp", (object)B10.Properties.ValidationMessages.WrongFile);
            }
        }

        [HttpPost]
        public ActionResult ProfileImage()
        {
            if (Request.Files.Count != 1 || Request.Files[0].ContentLength <= 0
                || !ImageHelper.IsCorrectContentType(Request.Files[0].ContentType))
                return View("Image");//View("PopUp", (object)B10.Properties.ValidationMessages.WrongFile);

            UserProfile profile = _db.GetProfile(UserHelper.UserId);
            if (profile == null)
                return new FileNotFoundResult();
            try
            {
                GalleryImage img = ImageHelper.SaveImage(Request.Files[0],
                    Path.Combine("Profile/",User.Identity.Name));
                img.ProfileId = profile.Id;
                _db.Add(img);
                _db.Save();
                return View("Image",img);
            }
            catch
            {
                return View("Image");//View("PopUp", (object)B10.Properties.ValidationMessages.WrongFile);
            }
        }



    }
}
